import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:hrf_app/common/api/file_upload/file_upload.dart';
import 'package:hrf_app/common/api/material/material.dart';
import 'package:hrf_app/common/models/bug/file_model.dart';
import 'package:hrf_app/common/routers/names.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/state_manager.dart';
import 'package:hrf_app/common/utils/addImageWaterUtil.dart';
import 'package:hrf_app/common/widgets/text_input_add.dart';
import 'package:hrf_app/common/widgets/text_input_multiple_add.dart';
import 'package:hrf_app/pages/menu/tool/image_water/imageWater/widgets/FileVoModel.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_watermark/image_watermark.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class ImageWaterController extends GetxController {
  ImageWaterController();

  List<FileVoModel> fileList = [];
  TextEditingController nameController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  TextEditingController remarkController = TextEditingController();
  Color selectedColor = Colors.black;

  _initData() {
    update(["imageWater"]);
  }

  Future<void> selectPhoto(ImageSource source) async {
    List<File> imageList = [];
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: source);
    if (pickedFile != null) {
      imageList.add(File(pickedFile.path));
    }
    await uploadImg(imageList);
  }

  Future<void> selectMultiImage() async {
    final picker = ImagePicker();
    final List<dynamic> pickedFileList = await picker.pickMultiImage();
    List<File> imageList = [];
    if (pickedFileList != null) {
      pickedFileList.forEach((file) {
        imageList.add(File(file.path));
      });
    }
    await uploadImg(imageList);
  }

  Future<void> uploadImg(List<File> imgList) async {
    for (var element in imgList) {
      // 压缩图片
      Uint8List? result =
          await FlutterImageCompress.compressWithFile(element.absolute.path,
              quality: 90, // 压缩质量，0-100
              minHeight: 1600,
              minWidth: 1600);

      FileVoModel fileVoModel = FileVoModel();
      File compressedFile = File("${element.path}_wfCompress.jpg");
      File fileCompress = await uint8ListToFile(result!, compressedFile!.path);
      fileVoModel.file = fileCompress;
      // 5. 配置水印样式
      final textStyle = ui.TextStyle(
          color: ui.Color.fromARGB(70, 0, 0, 0), // 半透明白色
 fontSize: 50,
          fontFamily: 'Roboto' // 确保字体可用
          );
      File fileWater = await AddImageWaterUtil.addImageWaterUnit8List(
          result!, element.path, '13863978230', textStyle);
      fileVoModel.addWaterFile = fileWater;
      fileList.add(fileVoModel);
      update(["imageWater"]);
    }
  }

  void delImage(int index) {
    fileList.removeAt(index); // 直接使用 removeAt 方法删除指定索引的元素
    update(["imageWater"]); // 确保调用 update 方法来触发 UI 重建
  }

  void selectImageOnTap() {
    // 弹出底部弹窗选择相机或相册
    Get.bottomSheet(
      Container(
        height: 150,
        alignment: Alignment.center,
        color: Colors.white,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ListTile(
              leading: const Icon(Icons.camera),
              title: const Text("相机"),
              onTap: () {
                selectPhoto(ImageSource.camera);
                Get.back(); // 关闭底部弹窗
              },
            ),
            ListTile(
              leading: const Icon(Icons.photo_library),
              title: const Text("相册"),
              onTap: () {
                selectMultiImage();
                Get.back(); // 关闭底部弹窗
              },
            ),
          ],
        ),
      ),
    );
  }

  imgView(index) {
    List<File> imageList = [];
    for (var vo in fileList) {
      imageList.add(vo.addWaterFile!);
    }
    TDImageViewer.showImageViewer(
        context: Get.context!,
        images: imageList,
        showIndex: true,
        deleteBtn: false,
        defaultIndex: index);
  }

  editItem(FileVoModel file) async{
    final image = await decodeImageFromList(file.addWaterFile!.readAsBytesSync());
    final imageHeight = image.height;
    final imageWidth = image.width;
    file.y = imageHeight - 160;
    Navigator.of(Get.context!).push(TDSlidePopupRoute(
        modalBarrierColor: TDTheme.of(Get.context!).fontGyColor2,
        slideTransitionFrom: SlideTransitionFrom.right,
        isDismissible: false,
        builder: (context) {
          return Container(
            color: Colors.grey[200],
            width: 280,
            child: ListView(children: [
              TDInput(
                  type: TDInputType.cardStyle,
                  width: 200,
                  controller: TextEditingController(text: file.title),
                  leftLabel: '文字',
                  contentAlignment: TextAlign.end,
                  hintText: '请输入文字',
                  onChanged: (val) {
                    file.title = val;
                    // 检查是否包含英文字符或数字
                    bool hasEnglishOrNumber = val.contains(RegExp(r'[a-zA-Z0-9]'));
                    // 根据是否包含英文/数字使用不同的系数计算长度
                    int fontLength = hasEnglishOrNumber ? val.length * 60 : val.length * 110;
                    file.x = imageWidth ~/ 2 - fontLength ~/ 2;
                  },
                  backgroundColor: Colors.white),
              TDCell(
                  arrow: false,
                  hover: false,
                  title: '水平间距',
                  rightIconWidget: TDStepper(
                    theme: TDStepperTheme.filled,
                    value: file.x,
                    max:10000,
                    size: TDStepperSize.large,
                    onChange: (value) {
                      file.x = value;
                    },
                  )),
              TDCell(
                  arrow: false,
                  hover: false,
                  title: '垂直间距',
                  rightIconWidget: TDStepper(
                    theme: TDStepperTheme.filled,
                    value: file.y,
                    max:10000,
                    size: TDStepperSize.large,
                    onChange: (value) {
                      file.y = value;
                    },
                  )),
              TDCell(
                  arrow: false,
                  hover: false,
                  title: '文字大小',
                  rightIconWidget: TDStepper(
                    theme: TDStepperTheme.filled,
                    value: file.fontSize,
                    size: TDStepperSize.large,
                    onChange: (value) {
                      file.fontSize = value;
                    },
                  )),
              TDCell(
                  hover: false,
                  title: '文字颜色',
                  rightIconWidget: TDButton(
                    icon: TDIcons.fill_color_1_filled,
                    style: TDButtonStyle(backgroundColor: file.color),
                    onTap: () {
                      openColorPicker(file);
                    },
                  )),
              Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 40, vertical: 20),
                  child: TDButton(
                    text: "保存",
                    theme: TDButtonTheme.primary,
                    onTap: () async {
                      // 5. 配置水印样式
                      final textStyle = ui.TextStyle(
                          color: ui.Color.fromARGB(70, 0, 0, 0), // 半透明白色
                 fontSize: 50,
                          fontFamily: 'Roboto' // 确保字体可用
                          );
                      File fileWater =
                          await AddImageWaterUtil.addImageWaterFile(
                              file.file!, '13863978230', textStyle);

                      final textStyleWater = ui.TextStyle(
                          color: file.color,
                          fontSize: file.fontSize.toDouble(),
                          fontFamily: 'Roboto' // 确保字体可用
                          );
                      File fileNew = await AddImageWaterUtil
                          .addTextWatermarkAtPositionFile(
                              fileWater,
                              file.title!,
                              textStyleWater,
                              file.x!.toDouble(),
                              file.y!.toDouble());
                      file.addWaterFile = fileNew;
                      update(["imageWater"]); // 确保调用 update 方法来触发 UI 重建
                      Navigator.of(context).pop();
                    },
                  ))
              //下面这行怎么写啊
            ]),
          );
        }));
  }

  Future<File> uint8ListToFile(Uint8List bytes, String filePath) async {
    File file = File(filePath);
    await file.writeAsBytes(bytes);
    return file;
  }

  handleCellClick() {
    print('点击了单元格:');
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  void saveMaterialDialog() {
    if (fileList.length == 0) {
      TDToast.showSuccess("请选择图片", context: Get.context!);
      return;
    }
    Navigator.of(Get.context!).push(TDSlidePopupRoute(
        modalBarrierColor: TDTheme.of(Get.context!).fontGyColor2,
        slideTransitionFrom: SlideTransitionFrom.top,
        builder: (context) {
          return Container(
              color: Colors.white,
              height: 300,
              child: ListView(children: [
                TextInputAdd(
                  leftLabel: "名称:",
                  required: true,
                  rightIconTapCallBack: () {},
                  hintText: "请输入名称",
                  controller: nameController,
                  contentAlignment: TextAlign.end,
                ),
                TextInputAdd(
                  leftLabel: "编码:",
                  hintText: "请输入编码",
                  controller: codeController,
                  contentAlignment: TextAlign.end,
                ),
                TextInputMultipleAdd(
                  leftLabel: "备注:",
                  hintText: "请输入备注",
                  controller: remarkController,
                  contentAlignment: TextAlign.start,
                ),
                Container(
                    padding: const EdgeInsets.symmetric(horizontal: 40),
                    child: TDButton(
                      text: '保存',
                      size: TDButtonSize.large,
                      type: TDButtonType.fill,
                      shape: TDButtonShape.rectangle,
                      theme: TDButtonTheme.primary,
                      onTap: () {
                        save();
                      },
                    ))
              ]));
        }));
  }

// 修改方法：将fileList中的图片下载到手机相册
  Future<void> downloadImagesToLocalByWater() async {
    for (var file in fileList) {
      final bytes = file.addWaterFile!.readAsBytesSync();
      await ImageGallerySaver.saveImage(bytes.buffer.asUint8List());
    }
    TDToast.showSuccess("保存成功", context: Get.context!);
    fileList = [];
    update(["imageWater"]); // 确保调用 update 方法来触发 UI 重建
  }

// 修改方法：将fileList中的图片下载到手机相册
  Future<void> downloadImagesToLocal() async {
    for (var file in fileList) {
      final bytes = file.file!.readAsBytesSync();
      await ImageGallerySaver.saveImage(bytes.buffer.asUint8List());
    }
    TDToast.showSuccess("保存成功", context: Get.context!);
    fileList = [];
    update(["imageWater"]); // 确保调用 update 方法来触发 UI 重建
  }

  Future<List<UploadFileModel>> uploadAndSaveImg(
      List<FileVoModel> imgList) async {
    // 单个文件上传
    List<MultipartFile> multipartFile = [];
    List<UploadFileModel> uploadFileModelList = [];
    for (var element in imgList) {
      // 压缩图片
      var result = await FlutterImageCompress.compressWithFile(
          element.file!.absolute.path,
          quality: 90,
          minHeight: 1600,
          minWidth: 1600);
      // 将压缩后的图片保存到临时文件
      var compressedFile = File("${element.file!.path}_compressed.jpg")
        ..writeAsBytesSync(result!);
      // 将压缩后的文件转换为 MultipartFile
      MultipartFile mfile = await MultipartFile.fromFile(
        compressedFile.path,
      );
      multipartFile.add(mfile);
    }
    FormData formData = FormData.fromMap(
        {'fileList': multipartFile, "fileFirstName": "material"});
    Map<String, dynamic> res = await UploadApi.simpleUploadListApi(formData);
    if (res["code"] == "00000") {
      List<dynamic> imgUrlMap = res['data'];
      for (var itemVo in imgUrlMap) {
        UploadFileModel uploadFileModel = UploadFileModel();
        uploadFileModel.url = itemVo["url"];
        uploadFileModelList.add(uploadFileModel);
      }
    }
    return uploadFileModelList;
  }

  save() async {
    Map saveMap = {};
    String name = nameController.text;
    String code = codeController.text;
    String remark = remarkController.text;
    saveMap['name'] = name;
    saveMap['code'] = code;
    saveMap['remark'] = remark;
    if (name == null || name == "") {
      TDToast.showWarning("请输入名称", context: Get.context!);
      return;
    }
    List<UploadFileModel> uploadFileModelList =
        await uploadAndSaveImg(fileList);
    saveMap['materialFileVoList'] = uploadFileModelList;
    print(saveMap.toString());
    MaterialApi.addMaterialApi(saveMap).then((res) {
      if (res["code"] == "00000") {
        Get.toNamed(RouteNames.materialAddPage);
        codeController = TextEditingController(text: '');
        nameController = TextEditingController(text: '');
        remarkController = TextEditingController(text: '');
      }
    });
  }

  // 打开颜色选择器
  void openColorPicker(FileVoModel file) {
    showDialog(
      context: Get.context!,
      builder: (context) {
        return AlertDialog(
          title: const Text('选择颜色'),
          content: SingleChildScrollView(
            child: ColorPicker(
              pickerColor: selectedColor,
              onColorChanged: (color) {
                file.color = color;
              },
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('确定'),
            )
          ],
        );
      },
    );
  }
}
